package com.thunder.reader.ui;

import com.thunder.reader.R;
import com.thunder.reader.provider.Feed;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AddFeedActivity extends Activity {
    private static final String TAG = "AddFeedActivity";
    public static final String EXTRA_SOURCE_ID = "extra_source_id";
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.add_feed_activity);
        boolean editFeed = false;
        int sourceId = -1;
        final Intent intent = getIntent();
        if (intent != null && intent.hasExtra(EXTRA_SOURCE_ID)) {
            sourceId = (int) intent.getLongExtra(EXTRA_SOURCE_ID, -1);
        }
        editFeed = (sourceId != -1);
        final TextView dialogTitle = (TextView) findViewById(R.id.add_feed_title);
        final EditText inputTitle = (EditText) findViewById(R.id.add_feed_input_title);
        final Button buttonSave = (Button) findViewById(R.id.add_feed_save);
        buttonSave.setEnabled(false);
        final Button buttonCancel = (Button) findViewById(R.id.add_feed_cancel);
        final EditText inputUrl = (EditText) findViewById(R.id.add_feed_input_url);
        inputUrl.addTextChangedListener(new TextWatcher(){
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    buttonSave.setEnabled(true);
                } else {
                    buttonSave.setEnabled(false);
                }
            }
        });
        final EditText inputFolder = (EditText) findViewById(R.id.add_feed_input_folder);
        if (editFeed) {
            // load info fill it to edit boxes
            dialogTitle.setText(R.string.edit_feed);
            final Uri sourceUri = ContentUris.withAppendedId(Feed.Source.CONTENT_URI, sourceId);
            final Cursor cursor = getContentResolver().query(sourceUri, 
                    new String[]{Feed.Source.TITLE, Feed.Source.FEED_URL, Feed.Source.GROUP_ID}, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                inputTitle.setText(cursor.getString(0));
                inputUrl.setText(cursor.getString(1));
                final int groupId = cursor.getInt(2);
                // TODO: use a better way to show folders
                final Cursor c = getContentResolver().query(ContentUris.withAppendedId(Feed.Group.CONTENT_URI, groupId), 
                        new String[]{Feed.Group.TITLE}, null, null, null);
                if (c != null && c.moveToFirst()) {
                    inputFolder.setText(c.getString(0));
                }
            }
        } else {
            dialogTitle.setText(R.string.add_feed);
        }
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        
        buttonSave.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // get all stuff and do enough validation before saving to database
                String url = inputUrl.getText().toString();
                if (TextUtils.isEmpty(url)) {
                    finish();
                }
                // TODO: do enough checking of url before write it to database, such as adding scheme
                if (!url.startsWith("http://")) {
                    url = "http://" + url;
                }
                final String title = inputTitle.getText().toString();
                String folder = inputFolder.getText().toString();
                final ContentValues cv = new ContentValues();
                cv.put(Feed.Source.TITLE, title);
                cv.put(Feed.Source.FEED_URL, url);
                // query for group id based on folder, if no, create one, if null put it into 'Uncategorized'
                String groupId = getGroupId(folder);
                cv.put(Feed.Source.GROUP_ID, groupId);
                getContentResolver().insert(Feed.Source.CONTENT_URI, cv);
                finish();
            }
        });
    }
    
    private String getGroupId(String folder) {
        String groupId;
        if (TextUtils.isEmpty(folder)) {
            folder = Feed.Group.GROUP_DEFAULT;
        }
        final Cursor cursor = getContentResolver().query(Feed.Group.CONTENT_URI, 
                new String[]{Feed.Group._ID}, Feed.Group.TITLE+"=?", new String[]{folder}, null);
        if (cursor == null || !cursor.moveToFirst()) {
            final ContentValues values = new ContentValues();
            values.put(Feed.Group.TITLE, Feed.Group.GROUP_DEFAULT);
            values.put(Feed.Group.DESCRIPTION, Feed.Group.GROUP_DEFAULT);
            final Uri uri = getContentResolver().insert(Feed.Group.CONTENT_URI, values);
            groupId = uri.getPathSegments().get(1);
        } else {
            groupId = cursor.getString(0);
            cursor.close();
        }
        return groupId;
    }
}